package org.sunnyleaf.votedemo.client;

import java.util.List;
import java.util.ArrayList;

import org.sunnyleaf.votedemo.client.data.LoginResponse;
import org.sunnyleaf.votedemo.client.data.Vote;
import org.sunnyleaf.votedemo.client.ui.VoteEditPanel;
import org.sunnyleaf.votedemo.client.ui.VoteListItemOwner;
import org.sunnyleaf.votedemo.client.ui.VoteListItemUser;
import org.sunnyleaf.votedemo.client.ui.VotePanel;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DecoratedTabPanel;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.datepicker.client.DatePicker;
/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Votedemo implements EntryPoint {

	public static enum UPDATE_TYPE{
		ADD,
		DELETE,
		UPDATE
	}
	
	// we use this token as a seperator and also a finger print of this program.
	public static final String SEC_TOKEN = "季沈戴胡";

	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while " + "attempting to contact the server. Please check your network " + "connection and try again.";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting
	 * service.
	 */
	private static final GreetingServiceAsync greetingService = GWT.create(GreetingService.class);

	
	private static String nickName;
	private static String email;
	
	private DecoratedTabPanel 		tabPanel;
	private VerticalPanel 			panelSponsoredVote;
	private VerticalPanel 			panelAttendedVote;
	private List<VoteListItemUser>	itemUserCompositList = new ArrayList<VoteListItemUser>();
	private List<VoteListItemOwner>	itemOwnerCompositList = new ArrayList<VoteListItemOwner>();
	
	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {

		String s = Window.Location.getParameter("vote");
		if (s != null && s.length() != 0) {
			showResult();
		} else {
			showMainPage();
		}

	}

	private void showMainPage() {

		greetingService.checkLogin(new AsyncCallback<LoginResponse>() {
			public void onFailure(Throwable caught) {
				Window.alert("Check Login Error");

			}

			public void onSuccess(LoginResponse result) {

				if (!result.isLoggedIn()) {
					Window.Location.replace(result.getLoginURL());
				} else {
					
					nickName = result.getNickName();
					email = result.getEmail();
					
					
					RootPanel.get().add(new HTML("<div>用户：" + result.getNickName() + ", Email: " + result.getEmail() + ", <a href='" + result.getLogoutURL() + "'>登出</a>" + "</div>"));
					RootPanel.get().add(new HTML("<div>投票系统</div>"));
					DockPanel dock = new DockPanel();
					dock.setSpacing(10);
					tabPanel = new DecoratedTabPanel();
					tabPanel.setWidth("700px");
					
					dock.add(tabPanel, DockPanel.CENTER);
					dock.setCellHorizontalAlignment( tabPanel, DockPanel.ALIGN_CENTER );
					dock.add( new DatePicker(), DockPanel.WEST );
				
					panelAttendedVote = new VerticalPanel();
					List<Vote> pvotes = result.getParticipatedVotes();
					List<Boolean> pvotedflag = result.getVotedFlag();
					if (pvotes.size() != 0) {
						int index = 0;
						for (Vote v : pvotes) {
							VoteListItemUser viu = new  VoteListItemUser(v, pvotedflag.get(index++) );
							viu.setVotedemo(getVotedemo());
							panelAttendedVote.add( viu );
							itemUserCompositList.add(viu);
						}
					} else {
						panelAttendedVote.add(new HTML("没有参加的投票"));
					}

					tabPanel.add(panelAttendedVote, "参加的投票");

					panelSponsoredVote = new VerticalPanel();
					List<Vote> ovotes = result.getOwnedVotes();
					if (ovotes.size() != 0) {
						for (Vote v : ovotes) {
							VoteListItemOwner vio = new VoteListItemOwner( v );
							vio.setMainPanel(getVotedemo());
							panelSponsoredVote.add( vio );
							itemOwnerCompositList.add( vio );
						}
					} else {
						panelSponsoredVote.add(new HTML("没有发起的投票"));
					}

					tabPanel.add(panelSponsoredVote, "发起的投票");

					VoteEditPanel vio = new VoteEditPanel();
					vio.setMainPanel(Votedemo.this);
					tabPanel.add(vio, "新建投票");

					tabPanel.selectTab(0);
					
					RootPanel.get().add( dock );
				}

			}
		});

	}
	
	private class AttendAsyncCallback<List> implements AsyncCallback<List>{

		private boolean bIsVoted;
		public AttendAsyncCallback( boolean isVoted ){
			bIsVoted = isVoted;
		}
		@Override
		public void onFailure(Throwable caught) {
			Window.alert(caught.getCause().getMessage());
		}

		@Override
		public void onSuccess( List result ) {
			panelAttendedVote.clear();
			java.util.List<Vote> votes = (java.util.List<Vote>)result;
			
			if( votes.size()!= 0 ){
				for( Vote v:votes ){
					VoteListItemUser viu = new VoteListItemUser(v, bIsVoted );
					panelAttendedVote.add(viu);
				}
			}			
		}
	}
	
	// 更新参加投票面板
	public void updateAttendVotePanel( Vote vote, UPDATE_TYPE type, boolean isVoted ){
		assert( vote != null );
//		if( vote.getId()==0 || type == UPDATE_TYPE.ADD ){
//			greetingService.getVotesAttendedBy(Votedemo.getEmail(), new AttendAsyncCallback<List<Vote>>(isVoted));
//		}
		if( type == UPDATE_TYPE.UPDATE ){
			// 更新现有UI
			for( VoteListItemUser viu : itemUserCompositList ){
				Vote v = viu.getVote();
				if( v.getStartDate().equals( vote.getStartDate() ) && v.getVoteName().equals(vote.getVoteName())){
					viu.setVote( vote );
					viu.setVotedemo(getVotedemo());
					viu.update(isVoted);
				}
			}
		}
		else if( type == UPDATE_TYPE.ADD ){
			// 增加新的投票
			VoteListItemUser viu = new  VoteListItemUser(vote, isVoted );
			viu.setVotedemo(getVotedemo());
			panelAttendedVote.add( viu );
			itemUserCompositList.add(viu);
			
		}
		else if( type == UPDATE_TYPE.DELETE ){
			// 删除UI
			for( VoteListItemUser viu:itemUserCompositList ){
				Vote v = viu.getVote();
				if( v.getStartDate().equals( vote.getStartDate() ) && v.getVoteName().equals( vote.getVoteName() )){
					panelAttendedVote.remove(viu);
				}
			}
		}
	}
	
	// 更新发起投票面板
	public void updateSponseredVotePanel(){
		// 查询当前用户所发起的所有投票
		greetingService.getVotesOwnsTo( Votedemo.email, new AsyncCallback<List<Vote>>(){
			public void onFailure(Throwable caught) {
				Window.alert("get votes error");
			}

			public void onSuccess(List<Vote> result) {
				panelSponsoredVote.clear();
				if (result.size() != 0) {
					for (Vote v : result) {
						VoteListItemOwner vio = new VoteListItemOwner(v);
						vio.setMainPanel( getVotedemo() );
						panelSponsoredVote.add(vio);
					}
				} else {
					panelSponsoredVote.add(new HTML("没有发起的投票"));
				}
			}
		});
		
		
	}
	
	public void activePanel( int index ){
		tabPanel.selectTab(index);
	}

	private void showResult() {
		RootPanel.get().add(new VotePanel());
	}

	static public String getNickName() {
		return nickName;
	}

	static public String getEmail() {
		return email;
	}
	
	public Votedemo getVotedemo(){
		return this;
	}

}
